'''
Created on 17 avr. 2013

@author: loic
'''

import os
from subprocess import Popen, PIPE
import curses, curses.textpad
from getch import getch

class mp3scan(object):
    '''
    classdocs
    '''


    def __init__(self, db):
        '''
        Constructor
        '''
        self.db = db
    def end(self):
        pass
    
    def show_artist(self, artist):
        print u'Artist : {0}'.format(artist)
        self.album_nb = 1
    def show_album(self, album, concat, size):
        print u'Album {0} : {1} ({2}) - {3}ko'.format(self.album_nb, album, concat, size)
        self.album_nb += 1
    def give_choice(self):
        print "Quit - Add 1 album to an other - New - nEw_old - Old - Split - noT_orig - Best - enFants - fLo"
        return getch()
    def add1album2another(self):
        print "Numero du 1er album:"
        while 1:
            r = getch()
            try:
                if int(r) in range(1, self.album_nb) or r == 'q':
                    break
                print r
            except ValueError:
                pass
        
        
    def scan_folder(self, directory):
        if directory == '.': directory = os.getcwd()
        one = os.listdir(directory)
        for artist in one:
            self.show_artist(artist.decode('utf-8'))
            dir_artist = directory+'/'+artist
            if not os.path.isdir(dir_artist):
                continue
            two = os.listdir(dir_artist)
            for album in two:
                dir_album = dir_artist+'/'+album
                if not os.path.isdir(dir_album):
                    continue
                s1 = Popen(['du', '-s', dir_album], stdout=PIPE).stdout.read()
                s2 = s1.split()
                size = int(s2[0])
                concat = u'%s_%s' % (artist.decode('utf-8'), album.decode('utf-8'))
                self.show_album(album.decode('utf-8'), concat, size)
            choice = self.give_choice()
            if choice == 'q':
                break
            if choice == 'a':
                self.add1album2another()
        self.end()
            
class mp3scanCurses(mp3scan):
    def __init__(self, db):
        import locale
        locale.setlocale(locale.LC_ALL, '')
        self.code = locale.getpreferredencoding()
        mp3scan.__init__(self, db)
        self.curses = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.curs_set(0)
    
    def end(self):
        curses.nocbreak(); curses.echo()
        curses.curs_set(1)
        curses.endwin()
        
    def show_artist(self, artist):
        self.curses.erase()
        self.artist = artist.encode(self.code)
        self.albums = []
        self.curses.addstr(0, 0, 'Artist : '+self.artist)
        self.album_nb = 1

    def show_album(self, album, concat, size):
        _album = album.encode(self.code)
        _concat = concat.encode(self.code)
        self.albums.append({'album': _album, 'concat': _concat,'size': size })
        self.curses.addstr(self.album_nb, 0, '{:<2} : {:<50.45}{} ko'.format(self.album_nb, _album, size))
        self.album_nb += 1

    def set_color(self, color):
        if curses.has_colors():
            n = color + 1
            curses.init_pair(n, color, curses.COLOR_BLACK)
            self.curses.attroff(curses.A_COLOR)
            self.curses.attron(curses.color_pair(n))
            
    def unset_color(self):
        if curses.has_colors():
            self.curses.attrset(curses.color_pair(0))
            
    def give_choice(self):
        self.curses.addstr(30, 0, 'Quit - Add 1 album to an other - New - nEw_old - Old - Split - noT_orig - Best - enFants - fLo')
        self.set_color(curses.COLOR_GREEN)
        self.curses.addch(30, 0, 'Q')
        self.curses.addch(30, 7, 'A')
        self.curses.addch(30, 33, 'N')
        self.curses.addch(30, 40, 'E')
        self.curses.addch(30, 49, 'O')
        self.curses.addch(30, 55, 'S')
        self.curses.addch(30, 65, 'T')
        self.curses.addch(30, 74, 'B')
        self.curses.addch(30, 83, 'F')
        self.curses.addch(30, 92, 'L')
        self.unset_color()
        self.curses.refresh()
        return chr(self.curses.getch())
        
    def maketextbox(self, h,w,y,x,value="",deco=None,textColorpair=0,decoColorpair=0):
    # thanks to http://stackoverflow.com/a/5326195/8482 for this
        nw = self.curses.subwin(h,w,y,x)
        txtbox = curses.textpad.Textbox(nw,insert_mode=True)
        if deco=="frame":
            self.curses.attron(decoColorpair)
            curses.textpad.rectangle(self.curses,y-1,x-1,y+h,x+w)
            self.curses.attroff(decoColorpair)
        elif deco=="underline":
            self.curses.hline(y+1,x,self.curses.ACS_HLINE,w,decoColorpair)
         
        nw.addstr(0,0,value,textColorpair)
        nw.attron(textColorpair)
        self.curses.refresh()
        return txtbox.edit()

    def add1album2another(self):
        from curses import panel
        win = self.curses.subwin(7, 50, 22, 20)
        pan = panel.new_panel(win)
        color = curses.COLOR_BLUE
        curses.init_pair(color, curses.COLOR_WHITE, curses.COLOR_BLUE)
        win.bkgdset(ord(' '), curses.color_pair(color))
        win.box()
        win.move(4, 1)
        win.addstr('First album')
        panel.update_panels()
        curses.doupdate()
        while True:
            choice = chr(self.curses.getch())
            if choice == ' ':
                choice = win.getstr()
            if choice == chr(27):
                choice = 'Q'
                break
            try:
                first = int(choice)
            except ValueError:
                first = 0
            if first in range(1, self.album_nb - 1):
                break
            win.addstr(0, 0, choice)
            panel.update_panels()
            curses.doupdate()
        win.addstr(1, 1, '1 : '+self.albums[first-1]['album'])
        panel.update_panels()
        curses.doupdate()
        win.addstr(4, 1, 'Second album')
        while True:
            choice = chr(self.curses.getch())
            if choice == ' ':
                choice = win.getstr()
            if choice == chr(27):
                choice = 'Q'
                break
            try:
                second = int(choice)
            except ValueError:
                second = 0
            if second in range(1, self.album_nb - 1):
                break
            win.addstr(0, 0, choice)
            panel.update_panels()
            curses.doupdate()
        win.addstr(2, 1, '1 : '+self.albums[second-1]['album'])
        panel.update_panels()
        curses.doupdate()
        newtxt = self.maketextbox(1, 45, 15, 20, self.albums[first-1]['album'], deco='frame')
        win.addstr(4, 1, newtxt)
       
        choice = chr(self.curses.getch())
            
        
        